package com.vichat.ccs.controller;

import com.vichat.ccs.vo.GridR;
import com.vichat.ccs.vo.JsonR;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.constant.I18nConstant;
import com.vichat.common.enums.RecordType;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.util.*;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.room.service.IRoomService;
import com.vichat.user.entity.*;
import com.vichat.user.service.IStaticDataService;
import com.vichat.user.service.IUserAgentService;
import com.vichat.user.service.IUserCcsService;
import com.vichat.user.service.IUserService;
import com.vichat.user.util.SessionUtils;
import com.vichat.user.vo.AgentUserOnlineVO;
import com.vichat.user.vo.UserCompanyVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping("/ccs/api")
public class CcsAgentController extends BaseController {
    ExecutorService tp = Executors.newCachedThreadPool();

    protected static final Logger logger = LoggerFactory.getLogger(CcsAgentController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private IUserCcsService userCcsService;


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }

    /**
     * 注册公司类型组织
     *
     * @param user
     * @param company
     * @return
     */
    @RequestMapping("/registerAgentCompany")
    @ResponseBody
    public JsonR registerCompany(AgentUser user, AgentCompany company) {
        JsonR json = new JsonR();
        try {
            CcsUser sessionUser = getSessionUser();
            String password = user.getPassword();
            if (StringUtils.isEmpty(password)) {
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_pwdNotEmpty, errorMsg);
            } else {
                userCcsService.registerAgentCompany(user, company);
                String opedInfo = "regist agent company ,company name：" + company.getCompanyName() + ",login account：" + user.getAccount();
                // 保存操作日志
                userCcsService.saveSysCcsBusiRecord(sessionUser, RecordType.CCSREGISTERAGENT, 1L, "ccs", opedInfo, opedInfo);

                json.setSuccess(true);
            }

        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 根据account、iccid、企业名查询企业信息
     *
     * @param company
     * @param user
     * @param pf
     * @return
     */
    @RequestMapping("/queryAgentCompany")
    @ResponseBody
    public GridR queryCompany(AgentUser user, AgentCompany company, PageFilter pf) {
        GridR grid = new GridR();
        try {
            AgentUser agentUser = null;
            List<AgentCompany> companyListFDB = userCcsService.queryAgentCompany(user, company, pf);
            if (companyListFDB != null && !companyListFDB.isEmpty()) {
                for (AgentCompany companyFDB : companyListFDB) {
                    agentUser = userCcsService.getAgentUserByAgentId(companyFDB.getAgentId(), GlobalConstant.USER_TYPE_1);
                    if (agentUser != null) {
                        companyFDB.setAccount(agentUser.getAccount());
                    }
                }
            }
            Long count = userCcsService.countAgentCompany(user, company);
            grid.setData(companyListFDB);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
        }
        return grid;
    }

    @RequestMapping("/getAgentCompany")
    @ResponseBody
    public JsonR getCompany(long agentId) {
        JsonR json = new JsonR();
        try {
            AgentCompany company = userCcsService.getAgentCompanyByAgentId(agentId);
            json.putData("company", company);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/saveAgentCompany")
    @ResponseBody
    public JsonR saveCompany(AgentCompany company) {
        JsonR json = new JsonR();
        try {
            userCcsService.saveAgentCompany(company);
            json.putData("company", company);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 修改用户账号
     *
     * @param agentId
     * @param password
     * @return
     */
    @RequestMapping("/chgAgentPassword")
    @ResponseBody
    public JsonR chgPassword(long agentId, String password) {
        JsonR json = new JsonR();
        try {
            if (StringUtils.isBlank(password)) {
                password = GlobalConstant.DEFAULT_PASSWORD;
            }
            AgentUser user = userCcsService.getAgentUserByAgentId(agentId,GlobalConstant.USER_TYPE_1);
            if (user == null) {
//                json.setMsg("未找到该账号，编号[" + uid + "]");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            } else {
                user.setPassword(password);
                encryptAgentUser(user);
                userCcsService.ccsChgAgentUserPass(user.getAgentUid(), user.getPassword());
                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 对UserBasic进行密码加密处理
     *
     * @param user
     */
    protected void encryptAgentUser(AgentUser user) {
        String mim = Md5Util.Md5Encode(user.getPassword(), null);
        mim = Md5Util.Md5Encode(mim, null);
        user.setPassword(mim);
    }

    @RequestMapping("/queryAgentUser")
    @ResponseBody
    public GridR queryAgentUser(AgentUser queryBean, PageFilter pf) {
        GridR grid = new GridR();
        try {
            if (NumberUtils.isNullOrZero(queryBean.getAgentId())) {
//                throw new Exception("请求参数不正确");
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            List<AgentUser> users = userCcsService.queryAgentUsers(queryBean, pf);
            Long count = userCcsService.countAgentUsers(queryBean);
            grid.setData(users);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 保存子账号
     *
     * @param user
     * @return
     */
    @RequestMapping("/saveAgentUser")
    @ResponseBody
    public JsonR saveAgentUser(AgentUser user) {
        JsonR json = new JsonR();
        try {

            CcsUser sessionUser = getSessionUser();
            StringBuffer opedInfo = new StringBuffer();
            if (!NumberUtils.isNullOrZero(user.getAgentUid())) {
                opedInfo.append("edit user");
            } else {
                opedInfo.append("create user");
            }
            AgentUser userFDB = userCcsService.saveAgentUser(user);

            opedInfo.append("：" + userFDB.getUserName());
            userCcsService.saveSysCcsBusiRecord(sessionUser, RecordType.CCSUSER, userFDB.getAgentUid(), userFDB.getUserName(), opedInfo.toString(), opedInfo.toString());

            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchCheckAgentUsers")
    @ResponseBody
    public JsonR batchCheckAgentUsers(@RequestBody List<AgentUser> users) {
        JsonR json = new JsonR();
        String errorCode = null;
        try {
            if (!users.isEmpty()) {
                ArrayList<AgentUser> successUsers = new ArrayList<AgentUser>();
                ArrayList<AgentUser> errorUsers = new ArrayList<AgentUser>();
                Set<String> accountSet = new HashSet<>();
                for (AgentUser user : users) {
                    AgentCompany company = userCcsService.getAgentCompanyByAgentId(user.getAgentId());
                    if (company == null) {
                        json.setI18nCode(I18nConstant.error_orgNotExist);
                        throw new Exception("数据异常，该企业组织信息错误,无根组织。请联系管理员处理，谢谢。");
                    }

                    errorCode = AgentUser.checkAgentUser(user);
                    if (errorCode != null) {
                        user.setExt1(errorCode);
                        errorUsers.add(user);
                        continue;
                    }

                    if (StringUtils.isNotBlank(user.getAccount())) {
                        AgentUser agentUserFDB = userCcsService.getAgentUserByAccount(user.getAccount());
                        if (agentUserFDB != null) {
                            user.setExt1(I18nConstant.error_accountIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                        if (accountSet.contains(user.getAccount())) {
                            user.setExt1(I18nConstant.error_accountIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                    } else {
                        user.setExt1(I18nConstant.error_accountNotEmpty);
                        errorUsers.add(user);
                        continue;
                    }
                    //到这里已经通过层层校验
                    accountSet.add(user.getAccount());
                    successUsers.add(user);//先加到list中
                }
                json.putData("successUsers", successUsers);
                json.putData("errorUsers", errorUsers);
            }

            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchSaveAgentUsers")
    @ResponseBody
    public JsonR batchSaveAgentUsers(@RequestBody List<AgentUser> user) throws IOException {
        JsonR json = new JsonR();
        try {
            Map<String, List<AgentUser>> resultMap = userCcsService.batchCreateAgentUser(user);
            json.putData("successUsers", resultMap.get("SUCCESS_LIST"));
            json.putData("errorUsers", resultMap.get("FAIL_LIST"));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchUpdateAgentUsers")
    @ResponseBody
    public JsonR batchUpdateAgentUsers(@RequestBody List<AgentUser> user) throws IOException {
        JsonR json = new JsonR();
        try {
            Map<String, List<AgentUser>> resultMap = userCcsService.batchUpdateAgentUser(user);
            json.putData("successUsers", resultMap.get("SUCCESS_LIST"));
            json.putData("errorUsers", resultMap.get("FAIL_LIST"));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchUpdateCompanyExpiredDate")
    @ResponseBody
    public JsonR batchUpdateCompanyExpiredDate(@RequestParam(value = "agentIds") long[] agentIds, Integer monthNumber, String record) {
        JsonR json = new JsonR();
        try {

            CcsUser sessionUser = getSessionUser();

            String opedInfo = null;

            for (long agentId : agentIds) {
                AgentCompany agentCompany = userCcsService.getAgentCompanyByAgentId(agentId);
                if(NumberUtils.isNullOrZero(agentCompany.getAuthMonth())){
                    agentCompany.setAuthMonth(0L);
                }
                if((agentCompany.getAuthMonth() + monthNumber) < 0 ){
                    opedInfo = "Agent recharge:" + agentCompany.getCompanyName() + ", amount:" + (int)(0 - agentCompany.getAuthMonth().longValue()) + " month";
                    userCcsService.updateExpiredDate(sessionUser, agentCompany, (int)(0 - agentCompany.getAuthMonth().longValue()), record);
                }else {
                    opedInfo = "Agent recharge:" + agentCompany.getCompanyName() + ", amount:" + monthNumber + " month";
                    userCcsService.updateExpiredDate(sessionUser, agentCompany, monthNumber, record);
                }
                userCcsService.saveSysCcsBusiRecord(sessionUser, RecordType.CCSRECHARGE, agentCompany.getAgentId(), agentCompany.getCompanyName(), opedInfo, opedInfo);
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/deleteAgentCompany")
    @ResponseBody
    public JsonR deleteAgentCompany(long agentId) {
        JsonR jsonR = new JsonR();
        try {
            UserPartyCompany company = new UserPartyCompany();
            company.setAgentId(agentId);
            company.setFreeType(null);
            long userCompanyNumber = userCcsService.countUserCompanyCCS(company, new UserBasic(), false);
            if (NumberUtils.isNotNullOrZero(userCompanyNumber)) {
                String errorMsg = I18NUtil.getMessage("error_agentNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_agentNotEmpty, errorMsg);
            }

            AgentCompany agentCompany = new AgentCompany();
            agentCompany.setParentId(agentId);
            long agentCompanyNumber = userCcsService.countAgentCompany(new AgentUser(), agentCompany);
            if (NumberUtils.isNotNullOrZero(agentCompanyNumber)) {
                String errorMsg = I18NUtil.getMessage("error_agentNotEmpty", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_agentNotEmpty, errorMsg);
            }

            AgentUser agentUser = new AgentUser();
            agentUser.setAgentId(agentId);
            List<AgentUser> userList = userCcsService.queryAgentUsers(agentUser, PageFilter.getMaxPageFilter());
            for (AgentUser agentUserFDB : userList) {
                userCcsService.deleteAgentUser(agentUserFDB.getAgentUid());
            }
            userCcsService.deleteAgent(agentId);
            jsonR.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setI18nCode(e.getCode());
            jsonR.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setCode(-9);
        }
        return jsonR;
    }
}
